/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package com.lcfgly.View;

import com.lcfgly.CustomBean.LoginForm;
import com.lcfgly.Dao.Product;
import com.lcfgly.Database.UserInfo;
import com.lcfgly.Exception.ActionException;
import com.lcfgly.Form.Validation.LoginValidation;
import com.lcfgly.Service.LoginService;
import com.lcfgly.util.VcodeImage;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

/**
 *
 * @author lcfgly
 */
@Controller
public class Login extends FatherController{
    
    @Autowired
    LoginService loginService;
    @Autowired
    Product product;
    
    /**
     * 登入页
     * @return 
     */
    @RequestMapping(value = "/login",method = RequestMethod.GET)
    public String Login(){
        return "controller/login";
    }
    
     /**
     * 输出验证码
     * @param request
     * @param response 
     */
    @RequestMapping(value = "/vcode")
    public void Vcode(HttpServletRequest request,HttpServletResponse response){
        response.setContentType("image/jpeg");//设置相应类型,告诉浏览器输出的内容为图片
        response.setHeader("Pragma", "No-cache");//设置响应头信息，告诉浏览器不要缓存此内容
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expire", 0);
        VcodeImage randomValidateCode = new VcodeImage();
        try {
            randomValidateCode.getRandcode(request, response);//输出图片方法
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    
    /**
     * 用户登入
     * @param login
     * @param res
     * @param request
     * @param response
     * @return
     * @throws ActionException 
     */
    @RequestMapping(value = "/login",method = RequestMethod.POST)
    public ModelAndView login(@Validated @ModelAttribute("loginform") LoginForm login,BindingResult res,HttpServletRequest request,HttpServletResponse response) throws ActionException{
        Cookie reuser = new Cookie("reuser", null);
        Cookie repwd=new Cookie("repwd", null);
        try {
            reuser.setValue(URLEncoder.encode(login.getUsername(), "utf-8"));
            repwd.setValue(URLEncoder.encode(login.getPassword(), "utf-8"));
        } catch (UnsupportedEncodingException unsupportedEncodingException) {
            Logger.getRootLogger().error(unsupportedEncodingException);
            reuser.setValue("");
            repwd.setValue("");
        }
        if(request.getParameter("reuser") != null){
            reuser.setMaxAge(30*24*60*60);
         }else{
            reuser.setMaxAge(0);
        }
        if(request.getParameter("repwd") != null){
            repwd.setMaxAge(30*24*60*60);
         }else{
            repwd.setMaxAge(0);
        }
        response.addCookie(repwd);
        response.addCookie(reuser);
        if(res.hasFieldErrors()){
            return new ModelAndView("controller/login","error",getError(res));
        }
        if(!login.getVcode().equalsIgnoreCase(request.getSession(true).getAttribute("vcode").toString()))
            throw new ActionException("验证码错误");
        UserInfo user=loginService.userLogin(login.getUsername(), login.getPassword());
        int x=product.getproductcount(user.getUid());
        if(x>0 && user.getRole() == 0)
            request.getSession(true).setAttribute("shopperfect", x);
        request.getSession(true).setAttribute("logininfo", user);
        return new ModelAndView("redirect:/control/productall.html");
    }
    
    /**
     * 绑定数据验证
     * @param binder 
     */
   @InitBinder("loginform")
    protected void initbinder(WebDataBinder binder) {
        binder.setValidator(new LoginValidation());
    }
    
    @RequestMapping(value = "/regedit",method = RequestMethod.GET)
    public String regedit(){
        return "regedit";
     }
    
    @RequestMapping(value = "/regedit",method = RequestMethod.POST)
    public ModelAndView regedit(@ModelAttribute("user") UserInfo user)throws ActionException{
        loginService.userRegister(user);
        return new ModelAndView("redirect:/login.html");
    }
    
}
